//
//  ValidateHelper.m
//  SCRM
//
//  Created by sotao on 14-9-29.
//  Copyright (c) 2014年 APP. All rights reserved.
//

#import "ValidateHelper.h"
#import "CommonCrypto/CommonDigest.h"
#import <AVFoundation/AVAssetImageGenerator.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <CoreFoundation/CoreFoundation.h>
@implementation ValidateHelper

#pragma mark - iPhone设备
+ (NSString *)deviceString{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    return platform;
}

#pragma mark - 验证输入是否为数字
+ (BOOL)isValidateNumber:(NSString *)number{
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
    NSString *filtered = [[number componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    BOOL basicTest = [number isEqualToString:filtered];
    if(!basicTest)
    {
        return NO;
    }
    return YES;
}

#pragma mark - 验证手机号码格式
+ (BOOL)isValidateMobile:(NSString *)mobile
{
    //    NSString *phoneRegex = @"^(13[0-9]|15[0|1|2|3|5|6|7|8|9]|18[0-9]|17[0|6|7|8]|14[4|7])\\d{8}$";
    NSString *phoneRegex = @"^(13[0-9]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9]|17[0|1|2|3|5|6|7|8|9]|14[0|1|2|3|5|6|7|8|9])\\d{8}$";
    NSPredicate *tempPhone = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [tempPhone evaluateWithObject:mobile];
}

#pragma mark - 验证邮箱格式
+ (BOOL)isValidateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *tempEmail = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [tempEmail evaluateWithObject:email];
}

#pragma mark - 验证密码格式
+ (BOOL)isValidatePassword:(NSString *)password
{
    NSString *emailRegex = @"^[a-zA-Z]\\w{5,17}$";
    NSPredicate *tempPassword = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [tempPassword evaluateWithObject:password];
}

#pragma mark - 验证double
+ (BOOL)isValidateDoubleStr:(NSString *)doubleStr
{
    NSString *emailRegex = @"^([0-9.]+)$";
    NSPredicate *tempPassword = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [tempPassword evaluateWithObject:doubleStr];
}

+(id)isValueNull:(id)value{
    if ([value isKindOfClass:[NSNull class]] || value == nil || value == NULL) {
        return nil;
    }else{
        return value;
    }
}

#pragma mark - 验证数据是否无效 如果无效返回默认类型数据
+(NSString *)judgeisNSStringNull:(id)value TypeCode:(NSInteger)typeCode{
    NSString *string = [NSString stringWithFormat:@"%@",value];
    if (string == nil || string == NULL || [string isEqualToString:@"<null>"]|| [string isEqualToString:@"(null)"]) {
        if (typeCode == 1)
            return @"";
        else if (typeCode == 2)
            return @"0";
    }
    if ([string isKindOfClass:[NSNull class]]) {
        if (typeCode == 1)
            return @"";
        else if (typeCode == 2)
            return @"0";
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) {
        if (typeCode == 1)
            return @"";
        else if (typeCode == 2)
            return @"0";
    }
    if (typeCode == 1)
        return string;
    else if (typeCode == 2)
        return [NSString stringWithFormat:@"%.1f",[value floatValue]];
    else
        return @"";
}


+ (UITextField *)textFieldValue0
{
    UITextField *tempTextField = [[UITextField alloc] initWithFrame:CGRectMake(90, 2, [UIScreen mainScreen].bounds.size.width - 210, 40)];
    tempTextField.borderStyle = UITextBorderStyleNone;
    tempTextField.font = [UIFont systemFontOfSize:15];
    //设置是否启动自动提醒更正功能
    tempTextField.autocorrectionType = UITextAutocorrectionTypeNo;
    tempTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    //编辑时出现修改x
    tempTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    //居中输入
    tempTextField.textAlignment = NSTextAlignmentRight;
    tempTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    //    tempTextField.delegate = self;
    tempTextField.keyboardType = UIKeyboardTypeDefault;
    tempTextField.returnKeyType = UIReturnKeyDone;
    return tempTextField;
}


+ (UITextField *)textFieldValue
{
    UITextField *tempTextField = [[UITextField alloc] initWithFrame:CGRectMake(90, 2, [UIScreen mainScreen].bounds.size.width - 108, 40)];
    tempTextField.borderStyle = UITextBorderStyleNone;
    tempTextField.font = [UIFont systemFontOfSize:15];
    //设置是否启动自动提醒更正功能
    tempTextField.autocorrectionType = UITextAutocorrectionTypeNo;
    tempTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    //编辑时出现修改x
    tempTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    //居中输入
    tempTextField.textAlignment = NSTextAlignmentRight;
    tempTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    //    tempTextField.delegate = self;
    tempTextField.keyboardType = UIKeyboardTypeDefault;
    tempTextField.returnKeyType = UIReturnKeyDone;
    return tempTextField;
}

+ (UITextField *)textFieldValue2
{
    UITextField *tempTextField = [[UITextField alloc] initWithFrame:CGRectMake(90, 2,[UIScreen mainScreen].bounds.size.width - 136, 40)];
    tempTextField.borderStyle = UITextBorderStyleNone;
    tempTextField.font = [UIFont systemFontOfSize:15];
    //设置是否启动自动提醒更正功能
    tempTextField.autocorrectionType = UITextAutocorrectionTypeNo;
    tempTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    //编辑时出现修改x
    tempTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    //居中输入
    tempTextField.textAlignment = NSTextAlignmentRight;
    tempTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    //    tempTextField.delegate = self;
    tempTextField.keyboardType = UIKeyboardTypeDefault;
    tempTextField.returnKeyType = UIReturnKeyDone;
    return tempTextField;
}

+(UILabel *)labelFieldValue:(NSString *)string{
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(270, 2, 40, 40)];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:14.0];
    label.numberOfLines = 0;
    label.lineBreakMode = 3;
    label.textAlignment = NSTextAlignmentRight;
    label.text = string;
    return label;
}

+(NSString *) dateFromDouble:(double)timeDouble
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    
    NSDate *tempEnd = [NSDate dateWithTimeIntervalSince1970:timeDouble];
    NSString *tempStr = [formatter stringFromDate:tempEnd];
    return tempStr;
}



+(id)readUserDefaultObjectValueForKey:(NSString*)aKey
{
    if (aKey) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSData *data = [defaults objectForKey:aKey];
        return [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    else {
        return nil;
    }
}

+(void)writeUserDefaultObjectValue:(NSObject*)aValue withKey:(NSString*)aKey
{
    if (!aValue || !aKey)
    {
        return;
    }
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSObject *objc = aValue ; // set value
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:objc];
    [defaults setObject:data forKey:aKey];
    [defaults synchronize];
}

+(void)clearUserDefaultWithKey:(NSString *)key
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
}


+(void)createList{
    
    NSString *cacheDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filename = [cacheDirectory stringByAppendingPathComponent:@"subscriptionHouse.plist"];
    
    NSFileManager * fileManager = [NSFileManager defaultManager];
    //判断文件是否存在
    //    if (![[NSFileManager defaultManager] fileExistsAtPath:filename]) {//如果文件不存在则创建
    //更改到待操作的目录下
    [fileManager changeCurrentDirectoryPath:[filename stringByExpandingTildeInPath]];
    //创建文件fileName文件名称，初始化 contents文件的内容，attributes文件的属性，初始为nil
    [fileManager createFileAtPath:filename contents:nil attributes:nil];
    //NSDictionary* dic = [NSDictionary dictionaryWithContentsOfFile:plistPath];
    
    //创建一个dic，写到plist文件里
    NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:@"House",@"house",nil];
    [dic writeToFile:filename atomically:YES];
    
}

+(void)writeUserDefaultHouseObjectValue:(NSObject*)aValue withKey:(NSString*)aKey
{
    NSString *cacheDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filename = [cacheDirectory stringByAppendingPathComponent:@"subscriptionHouse.plist"];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:filename]) {//如果文件不存在则创建
        if (!aKey)
        {
            return;
        }
        NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithContentsOfFile:filename];
        
        NSObject *objc = aValue ; // set value
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:objc];
        [tempDic setObject:data forKey:aKey];
        
        [tempDic writeToFile:filename atomically:YES];
    }
}


+(id)readUserDefaultHouseObjectValueForKey:(NSString*)aKey
{
    NSString *cacheDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filename = [cacheDirectory stringByAppendingPathComponent:@"subscriptionHouse.plist"];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:filename]) {//如果文件不存在则创建
        if (!aKey)
        {
            return nil;
        }
        //        NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithContentsOfFile:filename];
        
        //        for (NSMutableDictionary *temp in tempDic) {
        //        }
        //        NSObject *objc = aValue ; // set value
        //        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:objc];
        //        [tempDic setObject:data forKey:aKey];
        //
        //        [tempDic writeToFile:filename atomically:YES];
    }
    
    if (aKey) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSData *data = [defaults objectForKey:aKey];
        return [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    else {
        return nil;
    }
}


#pragma mark - label
+(NSAttributedString *)LabelColorCombinationsWithValues1:(NSString *)values1 Values2:(NSString *)values2 Values3:(NSString *)values3{
    NSMutableAttributedString *tempStr ;
    NSRange range1,range2,range3;
    if (![values3 isEqualToString:@""]) {
        range1.location = 0;
        range1.length = values1.length;
        range2.location = values1.length;
        range2.length = values2.length;
        range3.location = values2.length+values1.length;
        range3.length = values3.length;
        
        tempStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@%@",values1,values2,values3]];
        [tempStr addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xababab) range:NSMakeRange(range1.location,range1.length)];
        [tempStr addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xff5050) range:NSMakeRange(range2.location,range2.length)];
        [tempStr addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xababab) range:NSMakeRange(range3.location,range3.length)];
        [tempStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:12] range:NSMakeRange(range1.location,range1.length)];
        [tempStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13] range:NSMakeRange(range2.location,range2.length)];
        [tempStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:12] range:NSMakeRange(range3.location,range3.length)];
    }else{
        range1.location = 0;
        range1.length = values1.length;
        range2.location = values1.length;
        range2.length = values2.length;
        range3.location = values2.length;
        range3.length = values3.length;
        
        tempStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@",values1,values2]];
        [tempStr addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x646464) range:NSMakeRange(range1.location,range1.length)];
        [tempStr addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xff5050) range:NSMakeRange(range2.location,range2.length)];
        [tempStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:14] range:NSMakeRange(range1.location,range1.length)];
        [tempStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:15] range:NSMakeRange(range2.location,range2.length)];
    }
    
    return tempStr;
}

//3次MD5加密
+ (NSString *)myThreedMD5:(NSString *)str
{
    NSString *str1 = [ValidateHelper md5:str];
    NSString *str2 = [ValidateHelper md5:str1];
    NSString *str3 = [ValidateHelper md5:str2];
    
    return str3;
}

+(NSString *) md5: (NSString *) inPutText
{
    const char *cStr = [inPutText UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    // update MD5 有问题 请更改此处
    //    CC_MD5(cStr, strlen(cStr), result);
    
    
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
}


#pragma mark - 判断图片地址 有无http打头字符
+(BOOL)isHttpHead:(NSString *)urlStr{
    NSRange range = [urlStr rangeOfString:@"http"];
    NSRange ranges = [urlStr rangeOfString:@"https"];
 
    if (range.length > 1||ranges.length > 1 )
        return YES;
    else
        return NO;
}

#pragma mark -- 打印 组装http链接
+(void)httpgetUrlWithDic:(NSMutableDictionary *)tempDic httpUrlHead:(NSString *)httpUrlHead{
#ifdef DEBUG
    NSMutableString *tempStr = [NSMutableString stringWithCapacity:0];
    [tempStr appendFormat:httpUrlHead,nil];
    NSEnumerator * enumeratorKey = [tempDic keyEnumerator];
    for (NSObject *object in enumeratorKey) {
        NSString *tempkey = [NSString stringWithFormat:@"%@",object];
        NSString *tempValue = [NSString stringWithFormat:@"%@",[tempDic objectForKey:tempkey]];
        NSString *tempString = [NSString stringWithFormat:@"%@=%@&",tempkey,tempValue];
        [tempStr appendFormat:tempString,nil];
    }
    DMLog(@"http 请求链接 ＝ %@",tempStr);
#endif
}



#pragma mark - json字符串转为dictionary
+(NSMutableDictionary *)jsonStringToDictionary:(NSString *)parameter
{
    NSData *strData = [parameter dataUsingEncoding:NSUTF8StringEncoding];
    
    //ios5中自带的json解析
    NSError *error = nil;
    NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:strData options:NSJSONReadingMutableLeaves error:&error];
    
    //    //jsonkit中的json解析
    //    NSMutableDictionary *dict = [strData objectFromJSONData];
    
    return dict;
}

#pragma mark - 字典转换为json字符串
+(NSString *)dictionaryToJsonString:(NSDictionary *)dict
{
    NSString *jsonStr ;//= [dict JSONString];
    
    
    
    
    
    return jsonStr;
}

#pragma mark - NSString转换为NSData
+(NSData *)stringToData:(NSString *)str
{
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    return data;
}

#pragma mark - NSData转换为NSString
+(NSString *)dataToString:(NSData *)data
{
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return str;
}

////NSData转换为char
//+(char *)dataToChar:(NSData *)data
//{
//    char *myChar = [data bytes];
//    return myChar;
//}

#pragma mark - char转换为NSData
+(NSData *)charToData:(Byte *)byte
{
    byte = malloc(sizeof(Byte)*16);
    NSData *data = [NSData dataWithBytes:byte length:16];
    return data;
}

#pragma mark - 由 NSDate 转换为 NSString:
+(NSString *)dateToString:(NSDate *)theDate FormatterStr:(NSString *)formatterStr
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:formatterStr];
    NSString *dateStr = [dateFormatter stringFromDate:theDate];
    dateFormatter = nil;
    return dateStr;
}

#pragma mark - 由 NSString 转换为 NSDate:
+(NSDate *)stringToDate:(NSString *)dateStr FormatterStr:(NSString *)formatterStr
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //    @"yyyy-MM-dd HH:mm:ss"
    [dateFormatter setDateFormat:formatterStr];
    NSDate *theDate = [dateFormatter dateFromString:dateStr];
    dateFormatter = nil;
    return theDate;
}
+(NSInteger)cTimestampFromString:(NSString *)timeStr
                          format:(NSString *)format
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format];
    
    NSDate *date = [self dateFromString:timeStr format:format];
    return [self cTimestampFromDate:date];
}
+(NSInteger)cTimestampFromDate:(NSDate *)date
{
    return (long)[date timeIntervalSince1970];
}
+ (NSDate *)dateFromString:(NSString *)timeStr
                    format:(NSString *)format
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    [dateFormatter setDateFormat:format];
    NSDate *date = [dateFormatter dateFromString:timeStr];
    return date;
}
#pragma mark - 时间戳 转 时间格式字符串
+(NSString *)doubleConvertDate:(double)timeDouble FormatterStr:(NSString *)formatterStr
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:formatterStr];
    
    NSDate *tempEnd = [NSDate dateWithTimeIntervalSince1970:timeDouble];
    NSString *tempStr = [formatter stringFromDate:tempEnd];
    formatter = nil;
    return tempStr;
}

#pragma mark - 6位随机数验证码
//由于警告 此处强转double型
+ (int)randomCode
{
    srand((double)time(0));
    int i=rand()%900000+100000;
    return i;
}


//计算字符串固定宽度的高
+ (CGSize)sizeOfText:(NSString *)text theFont:(UIFont*)font theWidth:(float)width{
    CGSize textSize = {width,20000.0f};
    CGSize size;
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
    
    size =[text boundingRectWithSize:textSize options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
    return size;
}

//计算字符串宽高
+ (CGSize)sizeOfText:(NSString *)text theFont:(UIFont*)font{
    return [ValidateHelper sizeOfText:text theFont:font theWidth:20000.0f];
}

+(NSString *)aryToString:(NSMutableArray *)ary{
    NSString *b = @"";
    if(ary.count != 0){
        NSMutableString *string = [[NSMutableString alloc]init];
        for (int i = 0; i<ary.count; i++) {
            [string appendFormat:@"%@,",[ary objectAtIndex:i]];
        }
        b = [string substringToIndex:string.length-1];
    }
    return b;
}
//泡泡文本
+ (UIView *)bubbleView:(NSString *)text from:(BOOL)fromSelf withPosition:(int)position{
    
    //计算大小
    UIFont *font = [UIFont systemFontOfSize:14];
    CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(position, 20000.0f) lineBreakMode:NSLineBreakByWordWrapping];
    
    // build single chat bubble cell with given text
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
    returnView.backgroundColor = [UIColor clearColor];
    
    //背影图片
    UIImage *bubble = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fromSelf?@"1":@"1" ofType:@"png"]];
    
    UIImageView *bubbleImageView = [[UIImageView alloc] initWithImage:[bubble stretchableImageWithLeftCapWidth:floorf(bubble.size.width/2) topCapHeight:floorf(bubble.size.height/2)]];
    
    
    //添加文本信息
    UILabel *bubbleText = [[UILabel alloc] initWithFrame:CGRectMake(fromSelf?15.0f:22.0f,15, size.width+10, size.height+10)];
    bubbleText.backgroundColor = [UIColor clearColor];
    bubbleText.font = font;
    bubbleText.numberOfLines = 0;
    bubbleText.lineBreakMode = NSLineBreakByWordWrapping;
    bubbleText.text = text;
    bubbleText.textColor = UIColorFromRGB(0x666666);
    
    bubbleImageView.frame = CGRectMake(0.0f, 14.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+20.0f);
    
    if(fromSelf)
        returnView.frame = CGRectMake(SCRE_WIDTH-position-(bubbleText.frame.size.width+30.0f), 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    else
        returnView.frame = CGRectMake(position, 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    
    [returnView addSubview:bubbleImageView];
    [returnView addSubview:bubbleText];
    
    return returnView;
}
+ (NSString*)timeStringWith:(NSTimeInterval)timestamp multiLine:(BOOL)multi {
    if (timestamp > 1000000000000) {
        timestamp = timestamp / 1000;
    }
    
    static NSCalendar *calendar = nil;
    if (calendar == nil) {
        calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    }
    
    NSDate* dateGet = [NSDate dateWithTimeIntervalSince1970:timestamp];
    NSDate* dateNow = [NSDate date];
    
    unsigned int unitFlag = NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit| NSHourCalendarUnit | NSMinuteCalendarUnit;
    NSDateComponents *components = [calendar components:unitFlag fromDate:dateGet toDate:dateNow options:0];
    NSInteger days = [components day];
    NSInteger minute = [components minute];
    NSInteger hour = [components hour];
    
    NSString*   multiString = nil;
    if (multi) {
        multiString = @"\r\n";
    } else {
        multiString = @" ";
    }
    
    static NSDateFormatter* df = nil;
    if (df == nil) {
        df = [[NSDateFormatter alloc] init];
    }
    NSString* formatString = nil;
    // 今天
    if (days == 0) {
        if(minute < 5){
            formatString = @"刚刚";
        }else  if (hour == 0) {
            formatString = [NSString stringWithFormat:@"%ld分钟前",minute];
        }else{
            formatString = [NSString stringWithFormat:@"%ld小时前",hour];
        }
    } else if (days == 1) {
        // 昨天
        formatString = [NSString stringWithFormat:@"昨天%@HH:mm",multiString];
    } else if (days == 2) {
        // 前天
        formatString = [NSString stringWithFormat:@"前天%@HH:mm",multiString];
    } else {
        formatString = [NSString stringWithFormat:@"MM-dd%@",multiString];
    }
    [df setDateFormat:formatString];
    return [df stringFromDate:dateGet];
}

+ (NSString *)FilterExpression:(NSString *)html{
    NSArray *components = [html componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"[]"]];
    NSMutableArray *componentsToKeep = [NSMutableArray array];
    for (int i = 0; i < [components count]; i = i + 2) {
        [componentsToKeep addObject:[components objectAtIndex:i]];
    }
    NSString *plainText = [componentsToKeep componentsJoinedByString:@""];
    return plainText;
}


+ (void)ReplaceExpression:(NSString *)st label:(UITextView *)textview{
    textview.text = [self FilterExpression:st];
    NSArray *components = [st componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"[]"]];
    for (int i = 0; i < [components count]; i++) {
        NSString *str = [components objectAtIndex:i];
        if([str rangeOfString:@"emoji"].location !=NSNotFound){
            NSString *imgname = [components objectAtIndex:i];
            //Create emoji attachment
            EmojiTextAttachment *emojiTextAttachment = [EmojiTextAttachment new];
            emojiTextAttachment.emojiTag =[NSString stringWithFormat:@"[%@]",imgname];
            //Set tag and image
            emojiTextAttachment.image = [UIImage imageNamed:imgname];
            emojiTextAttachment.emojiSize = 18;
            //Insert emoji image
            UILabel *la = [[UILabel alloc]init];
            
            
            [textview.textStorage insertAttributedString:[NSAttributedString attributedStringWithAttachment:emojiTextAttachment]
                                                 atIndex:textview.selectedRange.location];
            //Move selection location
            textview.selectedRange = NSMakeRange(textview.selectedRange.location + 1, textview.selectedRange.length);
        }
    }
}

+ (void)ReplaceExpression:(NSString *)st label:(UITextView *)textview size:(int)size isr:(BOOL)isr{
    textview.text = isr?[NSString stringWithFormat:@":%@",[self FilterExpression:st]]:[self FilterExpression:st];
    NSArray *components = [st componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"[]"]];
    for (int i = 0; i < [components count]; i++) {
        NSString *str = [components objectAtIndex:i];
        if([str rangeOfString:@"emoji"].location !=NSNotFound){
            NSString *imgname = [components objectAtIndex:i];
            //Create emoji attachment
            EmojiTextAttachment *emojiTextAttachment = [EmojiTextAttachment new];
            emojiTextAttachment.emojiTag =[NSString stringWithFormat:@"[%@]",imgname];
            //Set tag and image
            emojiTextAttachment.image = [UIImage imageNamed:imgname];
            emojiTextAttachment.emojiSize = size ;
            emojiTextAttachment.bql = -2;
            //Insert emoji image
            [textview.textStorage insertAttributedString:[NSAttributedString attributedStringWithAttachment:emojiTextAttachment]
                                                 atIndex:textview.selectedRange.location];
            
            
            
            //Move selection location
            textview.selectedRange = NSMakeRange(textview.selectedRange.location + 1, textview.selectedRange.length);
        }
    }
}



+ (void)ReplaceExpression:(NSString *)st label:(UITextView *)textview size:(int)size{
    textview.text = [self FilterExpression:st];
    NSArray *components = [st componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"[]"]];
    for (int i = 0; i < [components count]; i++) {
        NSString *str = [components objectAtIndex:i];
        if([str rangeOfString:@"emoji"].location !=NSNotFound){
            NSString *imgname = [components objectAtIndex:i];
            //Create emoji attachment
            EmojiTextAttachment *emojiTextAttachment = [EmojiTextAttachment new];
            emojiTextAttachment.emojiTag =[NSString stringWithFormat:@"[%@]",imgname];
            //Set tag and image
            emojiTextAttachment.image = [UIImage imageNamed:imgname];
            emojiTextAttachment.emojiSize = size ;
            //Insert emoji image
            [textview.textStorage insertAttributedString:[NSAttributedString attributedStringWithAttachment:emojiTextAttachment]
                                                 atIndex:textview.selectedRange.location];
            //Move selection location
            textview.selectedRange = NSMakeRange(textview.selectedRange.location + 1, textview.selectedRange.length);
        }
    }
}

+(NSArray *)ReplaceMLEmojiLabel:(NSString *)st emojilable:(MLEmojiLabel *)emojilable{
    emojilable.numberOfLines = 0;
    emojilable.font = [UIFont systemFontOfSize:14.0f];
    emojilable.backgroundColor = [UIColor clearColor];
    emojilable.lineBreakMode = NSLineBreakByWordWrapping;
    emojilable.textColor = [UIColor blackColor];
    
    emojilable.textInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    
    emojilable.isNeedAtAndPoundSign = YES;
    emojilable.disableEmoji = NO;
    
    emojilable.lineSpacing = 3.0f;
    
    emojilable.verticalAlignment = TTTAttributedLabelVerticalAlignmentCenter;
    emojilable.customEmojiRegex = @"\\[[emoji_[0-9]{1,3}]+\\]";
    emojilable.customEmojiPlistName = @"expressionImage_custom.plist";
    [emojilable setText:[st trim]];
    return  [emojilable getEmojiNumber:st];
}
+(CGFloat )setimgeSize:(NSString *)url img:(UIImageView *)img{
     NSString *urls;
    if (![ValidateHelper isHttpHead:url]) {
        urls = [NSString stringWithFormat:@"%@%@",img_Url,url];
    }else{
        urls = url;
    }
//    [self setImage:urls img:img istoux:NO];

   
//    [img sd_setImageWithURL:[NSURL URLWithString:urls] placeholderImage:[UIImage imageNamed:@"notimgs"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
//        img.image = [ImageService compressedImages:image scaleSize:CGSizeMake(image.size.width, image.size.height*0.7)];
////        img.contentMode =  UIViewContentModeScaleAspectFill;
//        NSLog(@"%f",image.size.height);
//    }];
    
    CGImageRef inImageRef = [img.image CGImage];
    GLuint w = CGImageGetWidth(inImageRef);
    GLuint h = CGImageGetHeight(inImageRef);
    
    
 
    
  
    [self setImage:url img:img istoux:NO];
    return h;
    
}
+(NSString *)DistanceFormat:(NSString *)dis{
    if ([dis intValue]>1000) {
        dis = [NSString stringWithFormat:@"%dkm",[dis intValue]/1000];
        return dis;
    }else{
        return  [NSString stringWithFormat:@"%dm",[dis intValue]];
    }
}

+(MPMoviePlayerController *)bofang:(NSURL *)url{
    // 设置视频播放器
    MPMoviePlayerController  *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
    moviePlayer.allowsAirPlay = YES;
    [moviePlayer requestThumbnailImagesAtTimes:@[@0.0,@1.0] timeOption:MPMovieTimeOptionNearestKeyFrame];
    
    moviePlayer.scalingMode = MPMovieScalingModeAspectFill;
    [moviePlayer.view setFrame:CGRectMake(0,SCRE_HEIGHT/2-SCRE_WIDTH/2, SCRE_WIDTH, SCRE_WIDTH)];
    // 将moviePlayer的视图添加到当前视图中
    moviePlayer.controlStyle = MPMovieControlStyleNone;
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, SCRE_HEIGHT-80, SCRE_WIDTH, 80)];
    view.backgroundColor = [UIColor blackColor];
    [moviePlayer.view addSubview:view];
    [moviePlayer play];
    return moviePlayer;
}

+(NSString *)stringAge:(NSString *)str{
    NSArray *s = [str componentsSeparatedByString:@"-"];
    NSDate *  senddate=[NSDate date];
    
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:@"YYYY"];
    
    NSString *  basetime =[dateformatter stringFromDate:senddate];
    return [NSString stringWithFormat:@"%d,%d",[basetime intValue] - [[s firstObject] intValue],[basetime intValue] - [[s lastObject] intValue]];
    
}
+ (void) hideTabBar:(UITabBarController *) tabbarcontroller
{
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    float fHeight = screenRect.size.height;
    if(UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation) )
    {
        fHeight = screenRect.size.width;
    }
    
    for(UIView *view in tabbarcontroller.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
        {
            [view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)];
        }
        else
        {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, fHeight)];
            view.backgroundColor = [UIColor blackColor];
        }
    }
    [UIView commitAnimations];
}



+ (void) showTabBar:(UITabBarController *) tabbarcontroller
{
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    float fHeight = screenRect.size.height - tabbarcontroller.tabBar.frame.size.height;
    
    if(UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation) )
    {
        fHeight = screenRect.size.width - tabbarcontroller.tabBar.frame.size.height;
    }
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    for(UIView *view in tabbarcontroller.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
        {
            [view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)];
        }
        else
        {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, fHeight)];
        }
    }
    [UIView commitAnimations];
}
+ (UIImage*) thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode =AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:NULL error:&thumbnailImageGenerationError];
    
    if(!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);
    UIImage*thumbnailImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage:thumbnailImageRef] : nil;
    return thumbnailImage;
}
+(NSString *)numberFormat:(NSString *)number{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = kCFNumberFormatterCurrencyStyle;
    return  [formatter stringFromNumber:[NSNumber numberWithInt:[number intValue]]];
}
+(CGFloat)GetJiaoDu:(MyLatLng *)A b:(MyLatLng *)B{
    double dx=(B.m_RadLo-A.m_RadLo)*A.Ed;
    double dy=(B.m_RadLa-A.m_RadLa)*A.Ec;
    double angle=0.0;
    angle=atan(fabs(dx/dy))*180./M_PI;
    double dLo=B.m_Longitude-A.m_Longitude;
    double dLa=B.m_Latitude-A.m_Latitude;
    if(dLo>0&&dLa<=0){
        angle=(90.-angle)+90;
    }
    else if(dLo<=0&&dLa<0){
        angle=angle+180.;
    }else if(dLo<0&&dLa>=0){
        angle= (90.-angle)+270;
    }
    return angle;
    
}
+(NSMutableDictionary *)outFangxiang:(MyLatLng *)A b:(MyLatLng *)B{
    CGFloat jiaodu = [self GetJiaoDu:A b:B];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    if ((jiaodu > 67 ) && (jiaodu <= 112)) [dic setObject:@"东" forKey:@"p"];
    if ((jiaodu > 22) && (jiaodu <= 67)) [dic setObject:@"东北" forKey:@"p"];
    if ((jiaodu > 337) || (jiaodu <= 22)) [dic setObject:@"北" forKey:@"p"];
    if ((jiaodu > 292) && (jiaodu <= 337)) [dic setObject:@"西北" forKey:@"p"];
    if ((jiaodu > 247) && (jiaodu <= 292)) [dic setObject:@"西" forKey:@"p"];
    if ((jiaodu > 202) && (jiaodu <= 247)) [dic setObject:@"西南" forKey:@"p"];
    if ((jiaodu > 157) && (jiaodu <= 202)) [dic setObject:@"南" forKey:@"p"];
    if ((jiaodu > 112) && (jiaodu <= 157)) [dic setObject:@"东南" forKey:@"p"];
    [dic setObject:[NSString stringWithFormat:@"%f",jiaodu] forKey:@"jd"];
    return dic;
}

+(void)colorLable:(UILabel *)lable str:(NSString *)str key:(NSString *)key{
    NSMutableAttributedString *strs = [[NSMutableAttributedString alloc] initWithString:str];
    NSRange r = [str rangeOfString:key];
    [strs addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:r];
    lable.attributedText = strs;
}
+(void)colorLable:(UILabel *)lable str:(NSString *)str key:(NSString *)key color:(UIColor *)color size:(int)size{
    NSMutableAttributedString *strs = [[NSMutableAttributedString alloc] initWithString:str];
    NSRange r = [str rangeOfString:key];
    [strs addAttribute:NSForegroundColorAttributeName value:color range:r];
    [strs addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:size] range:r];
    lable.attributedText = strs;
}

+(NSString *)timeToAge:(NSString *)time{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    //生日
    NSDate *birthDay = [dateFormatter dateFromString:[ValidateHelper dateFromDouble:[time doubleValue]]];
    //当前时间
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    NSDate *currentDate = [dateFormatter dateFromString:currentDateStr];
    NSTimeInterval times =[currentDate timeIntervalSinceDate:birthDay];
    int age = ((int)times)/(3600*24*365);
    return [NSString stringWithFormat:@"%d",age];
}
+(void)setImage:(NSString *)url img:(UIImageView *)img istoux:(BOOL)istx{
    
    [img sd_setImageWithURL:[NSURL URLWithString:url]
           placeholderImage:[UIImage imageNamed:istx?@"mrtx":@"notimgs"]];
    
//    img.image = [ImageService resizeImage:img.image toSize:CGSizeMake(img.frame.size.width, img.frame.size.height)];
    
}

+(NSString *)getID{
    NSString * strUUID = (NSString *)[SFHFKeychainUtils load:@"com.company.app.usernamepassword"];
    //首次执行该方法时，uuid为空
    if ([strUUID isEqualToString:@""] || !strUUID)
    {
        //生成一个uuid的方法
        CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
        
        strUUID = (NSString *)CFBridgingRelease(CFUUIDCreateString (kCFAllocatorDefault,uuidRef));
        
        //将该uuid保存到keychain
        [SFHFKeychainUtils save:KEY_USERNAME_PASSWORD data:strUUID];
        
    }
    return strUUID;
    
}
//获取拼音首字母(传入汉字字符串, 返回大写拼音首字母)
+ (NSString *)firstCharactor:(NSString *)aString
{
    if (aString.length == 0||[aString isKindOfClass:[NSNull class]]) {
        return @"";
    }
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pinYin = [str capitalizedString];
    //获取并返回首字母
    return [pinYin substringToIndex:1];
}



+(NSMutableArray *)dataFrom:(NSMutableArray *)ary{
    KCContactGroup *A;
    KCContactGroup *B;
    KCContactGroup *C;
    KCContactGroup *D;
    KCContactGroup *E;
    KCContactGroup *F;
    KCContactGroup *G;
    KCContactGroup *H;
    KCContactGroup *I;
    KCContactGroup *J;
    KCContactGroup *K;
    KCContactGroup *L;
    KCContactGroup *M;
    KCContactGroup *N;
    KCContactGroup *O;
    KCContactGroup *P;
    KCContactGroup *Q;
    KCContactGroup *R;
    KCContactGroup *S;
    KCContactGroup *T;
    KCContactGroup *U;
    KCContactGroup *W;
    KCContactGroup *V;
    KCContactGroup *X;
    KCContactGroup *Y;
    KCContactGroup *Z;
    NSMutableArray *arys = [[NSMutableArray alloc]init];
    for (int i = 0; i<ary.count; i++) {
        LoginResponseModel *model = [[LoginResponseModel alloc] init];
        if (![[ary objectAtIndex:i] isKindOfClass:[LoginResponseModel class]]) {
            [model serializationWithDictionary:[ary objectAtIndex:i]];
        }else{
            model = [ary objectAtIndex:i];
        }
        NSString *str = [self firstCharactor:model.nickname];
        if ([str isEqualToString:@"A"]) {
            if (A) {
                [A.contacts addObject:model];
            }else{
                A = [KCContactGroup initWithName:@"A" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"B"]){
            if (B) {
                [B.contacts addObject:model];
            }else{
                B = [KCContactGroup initWithName:@"B" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"C"]){
            if (C) {
                [C.contacts addObject:model];
            }else{
                C = [KCContactGroup initWithName:@"C" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"D"]){
            if (D) {
                [D.contacts addObject:model];
            }else{
                D = [KCContactGroup initWithName:@"D" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"E"]){
            if (E) {
                [E.contacts addObject:model];
            }else{
                E = [KCContactGroup initWithName:@"E" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"F"]){
            if (F) {
                [F.contacts addObject:model];
            }else{
                F = [KCContactGroup initWithName:@"F" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"G"]){
            if (G) {
                [G.contacts addObject:model];
            }else{
                G = [KCContactGroup initWithName:@"G" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"H"]){
            if (H) {
                [H.contacts addObject:model];
            }else{
                H = [KCContactGroup initWithName:@"H" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"I"]){
            if (I) {
                [I.contacts addObject:model];
            }else{
                I = [KCContactGroup initWithName:@"I" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if([str isEqualToString:@"J"]){
            if (J) {
                [J.contacts addObject:model];
            }else{
                J = [KCContactGroup initWithName:@"J" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"K"]){
            if (K) {
                [K.contacts addObject:model];
            }else{
                K = [KCContactGroup initWithName:@"K" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"L"]){
            if (L) {
                [L.contacts addObject:model];
            }else{
                L = [KCContactGroup initWithName:@"L" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"M"]){
            if (M) {
                [M.contacts addObject:model];
            }else{
                M = [KCContactGroup initWithName:@"M" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"N"]){
            if (N) {
                [N.contacts addObject:model];
            }else{
                N = [KCContactGroup initWithName:@"N" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"O"]){
            if (O) {
                [O.contacts addObject:model];
            }else{
                O = [KCContactGroup initWithName:@"O" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"P"]){
            if (P) {
                [P.contacts addObject:model];
            }else{
                P = [KCContactGroup initWithName:@"P" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"Q"]){
            if (Q) {
                [Q.contacts addObject:model];
            }else{
                Q = [KCContactGroup initWithName:@"Q" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"R"]){
            if (R) {
                [R.contacts addObject:model];
            }else{
                R = [KCContactGroup initWithName:@"R" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"S"]){
            if (S) {
                [S.contacts addObject:model];
            }else{
                S = [KCContactGroup initWithName:@"S" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"T"]){
            if (T) {
                [T.contacts addObject:model];
            }else{
                T = [KCContactGroup initWithName:@"T" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"U"]){
            if (U) {
                [U.contacts addObject:model];
            }else{
                U = [KCContactGroup initWithName:@"U" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"V"]){
            if (V) {
                [V.contacts addObject:model];
            }else{
                V = [KCContactGroup initWithName:@"V" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"W"]){
            if (W) {
                [W.contacts addObject:model];
            }else{
                W = [KCContactGroup initWithName:@"W" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"X"]){
            if (X) {
                [X.contacts addObject:model];
            }else{
                X = [KCContactGroup initWithName:@"X" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"Y"]){
            if (Y) {
                [Y.contacts addObject:model];
            }else{
                Y = [KCContactGroup initWithName:@"Y" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }else if ([str isEqualToString:@"Z"]){
            if (Z) {
                [Z.contacts addObject:model];
            }else{
                Z = [KCContactGroup initWithName:@"Z" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
            }
        }
        //xhw2018-1-30加
//        else {
//            if (A) {
//                [A.contacts addObject:model];
//            }else{
//                A = [KCContactGroup initWithName:@"A" andDetail:@"" andContacts:[NSMutableArray arrayWithObjects:model, nil]];
//            }
//        }
    }
    if (A) {
        [arys addObject:A];
    } if (B){
        [arys addObject:B];
        
    } if (C){
        [arys addObject:C];
        
    } if (D){
        [arys addObject:D];
        
    } if (E){
        [arys addObject:E];
        
    } if (F){
        [arys addObject:F];
        
    } if (G){
        [arys addObject:G];
        
    } if (H){
        [arys addObject:H];
        
    }
    
    if (I){
        [arys addObject:I];
        
    } if (J){
        [arys addObject:J];
        
    } if (K){
        [arys addObject:K];
        
    } if (M){
        [arys addObject:M];
        
    } if (R){
        [arys addObject:R];
        
    } if (N){
        [arys addObject:N];
        
    } if (O){
        [arys addObject:O];
        
    } if (P){
        [arys addObject:P];
        
    }
    
    if (L){
        [arys addObject:L];
        
    } if (S){
        [arys addObject:S];
        
    } if (T){
        [arys addObject:T];
        
    } if (U){
        [arys addObject:U];
        
    } if (V){
        [arys addObject:V];
        
    } if (W){
        [arys addObject:W];
        
    } if (X){
        [arys addObject:X];
        
    } if (Y){
        [arys addObject:Y];
        
    } if (Z){
        [arys addObject:Z];
    }
    
    
    
    return arys;
    
}


+ (NSMutableDictionary  *)GetHtmlImgOrTitle:(NSString *)html;
{
    
    
    NSString *u = html;
    NSString *Url;
    if ([ValidateHelper isHttpHead:u]) {
        NSArray *p = [u componentsSeparatedByString:@"//"];
        u = [p lastObject];
        NSRange rangew = [u rangeOfString:@"www"];
        if(rangew.length<1){
            Url = [NSString stringWithFormat:@"www.%@",u];
        }
        if (![ValidateHelper isHttpHead:Url]) {
            Url = [NSString stringWithFormat:@"http://%@",Url];
        }
    }else{
        NSRange rangew = [u rangeOfString:@"www"];
        if(rangew.length<1){
            Url = [NSString stringWithFormat:@"www.%@",u];
        }
        if (![ValidateHelper isHttpHead:Url]) {
            Url = [NSString stringWithFormat:@"http://%@",Url];
        }
    }
    html = Url;
    
    NSError *err = nil;
    NSString *str = [NSString stringWithContentsOfURL:[NSURL URLWithString:html] encoding:NSUTF8StringEncoding error:&err];
    if (err == nil)
    {
        html = str;
        NSMutableArray *resultArray = [NSMutableArray array];
        
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<(img|IMG)(.*?)(/>|></img>|>)" options:NSRegularExpressionAllowCommentsAndWhitespace error:nil];
        NSArray *result = [regex matchesInString:html options:NSMatchingReportCompletion range:NSMakeRange(0, html.length)];
        
        for (NSTextCheckingResult *item in result) {
            NSString *imgHtml = [html substringWithRange:[item rangeAtIndex:0]];
            
            NSArray *tmpArray = nil;
            if ([imgHtml rangeOfString:@"src=\""].location != NSNotFound) {
                tmpArray = [imgHtml componentsSeparatedByString:@"src=\""];
            } else if ([imgHtml rangeOfString:@"src="].location != NSNotFound) {
                tmpArray = [imgHtml componentsSeparatedByString:@"src="];
            }
            
            if (tmpArray.count >= 2) {
                NSString *src = tmpArray[1];
                
                NSUInteger loc = [src rangeOfString:@"\""].location;
                if (loc != NSNotFound) {
                    src = [src substringToIndex:loc];
                    NSRange rangew = [src rangeOfString:@"//"];

                    if (rangew.length > 1) {
                        NSArray *p = [src componentsSeparatedByString:@"//"];
                        [resultArray addObject:[p lastObject]];
                    }else{
                        [resultArray addObject:src];
                    }
                }
            }
        }
        NSRegularExpression *r = [NSRegularExpression regularExpressionWithPattern:@"<title>[^<>]*</title>" options:NSRegularExpressionAllowCommentsAndWhitespace error:nil];
        NSArray *rs = [r matchesInString:html options:NSMatchingReportCompletion range:NSMakeRange(0, html.length)];
        if (rs.count == 0) {
            return nil;
        }
        NSString *title;
        for (NSTextCheckingResult *item in rs) {
            NSString *imgHtml = [html substringWithRange:[item rangeAtIndex:0]];
            title = [ValidateHelper cleanlHTML:imgHtml];
            break;
        }
        
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setObject:[resultArray firstObject] forKey:@"img"];
        [dic setObject:title forKey:@"title"];
        
        return dic;
    }
    return nil;
}

+ (NSString *)cleanlHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">" intoString:&text];
        //替换字符
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    //    NSString * regEx = @"<([^>]*)>";
    //    html = [html stringByReplacingOccurrencesOfString:regEx withString:@""];
    return html;
}


+ (NSString *)distanceTimeWithBeforeTime:(double)beTime
{
    NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
    double distanceTime = now - beTime;
    NSString * distanceStr;
    
    NSDate * beDate = [NSDate dateWithTimeIntervalSince1970:beTime];
    NSDateFormatter * df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"HH:mm"];
    NSString * timeStr = [df stringFromDate:beDate];
    
    [df setDateFormat:@"dd"];
    NSString * nowDay = [df stringFromDate:[NSDate date]];
    NSString * lastDay = [df stringFromDate:beDate];
    
    if (distanceTime < 60) {//小于一分钟
        distanceStr = @"刚刚";
    }
    else if (distanceTime <60*60) {//时间小于一个小时
        distanceStr = [NSString stringWithFormat:@"%ld分钟前",(long)distanceTime/60];
    }
    else if(distanceTime <24*60*60 && [nowDay integerValue] == [lastDay integerValue]){//时间小于一天
        distanceStr = [NSString stringWithFormat:@"今天 %@",timeStr];
    }
    else if(distanceTime<24*60*60*2 && [nowDay integerValue] != [lastDay integerValue]){
        
        if ([nowDay integerValue] - [lastDay integerValue] ==1 || ([lastDay integerValue] - [nowDay integerValue] > 10 && [nowDay integerValue] == 1)) {
            distanceStr = [NSString stringWithFormat:@"昨天 %@",timeStr];
        }
        else{
            [df setDateFormat:@"MM-dd HH:mm"];
            distanceStr = [df stringFromDate:beDate];
        }
        
    }
    else if(distanceTime <24*60*60*365){
        [df setDateFormat:@"MM-dd HH:mm"];
        distanceStr = [df stringFromDate:beDate];
    }
    else{
        [df setDateFormat:@"yyyy-MM-dd HH:mm"];
        distanceStr = [df stringFromDate:beDate];
    }
    return distanceStr;
}

//xhw12月19号加:
+(UIImage*)imageFromSdcache:(NSString *)urlStr{
    
    NSData*imageData =nil;
    
    BOOL isExit = [[SDWebImageManager sharedManager] diskImageExistsForURL:[NSURL URLWithString:urlStr]];
    
    if(isExit) {
        
        NSString*cacheImageKey = [[SDWebImageManager sharedManager]cacheKeyForURL:[NSURL URLWithString:urlStr]];
        
        if(cacheImageKey.length) {
            
            NSString *cacheImagePath = [[SDImageCache sharedImageCache] defaultCachePathForKey:cacheImageKey];
            
            if(cacheImagePath.length) {
                
                imageData = [NSData dataWithContentsOfFile:cacheImagePath];
                
            }
            
        }
        
    }
    
    if(!imageData) {
        
        imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]];
        
    }
    
    UIImage *image = [UIImage imageWithData:imageData];
    
    return image;
    
}

+ (NSString *)GetWifiName{
    
    NSString *wifiName = @"Not Found";
    
    CFArrayRef myArray = CNCopySupportedInterfaces();
    
    if (myArray != nil) {
        
        CFDictionaryRef myDict =CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
        
        if (myDict != nil) {
            
            NSDictionary *dict = (NSDictionary*)CFBridgingRelease(myDict);
            
            wifiName = [dict valueForKey:@"SSID"];
            
        }
        
        NSLog(@"wifiName:%@", wifiName);
    }
    return wifiName;
}

+(BOOL)isMobileNum: (NSString *)strMobile {
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    return [regextestmobile evaluateWithObject:strMobile];
}
@end
